package 面试.可重入锁;
/**
 * 实现一个可重入锁
 */

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class Mylock implements Lock {

    boolean islocked=false;
    int lockcount=0;
    Thread lockThread;
    @Override
    public void lock() {
      Thread thread=Thread.currentThread();
      while (islocked&&lockThread!=thread){
          try {
              wait();
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }

      islocked=true;
      lockcount++;
      lockThread=thread;
    }

    @Override
    public void unlock() {
        Thread thread=Thread.currentThread();
       if(lockThread==thread){
           lockcount--;
           if(lockcount==0){
               notify();
               islocked=false;
           }
       }
    }


    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }


    @Override
    public Condition newCondition() {
        return null;
    }
}
